package com.alogic.terminal.xscript;

import com.alogic.terminal.Command;
import com.alogic.terminal.Resolver;
import com.alogic.terminal.Terminal;
import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.BaseException;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;


/**
 * 执行指令，并将指令的输出结果存入变量
 *
 * @since 1.6.13.38 [20210224 duanyy] <br>
 */
public class XCmdOut extends AbstractLogiclet {
    protected String pid = "$xshell";
    protected String id;

    protected String $cmd;
    protected String $dft;

    public XCmdOut(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);

        pid = PropertiesConstants.getString(p,"pid", pid , true);
        id = PropertiesConstants.getString(p,"id","$" + this.getXmlTag(),true);
        $cmd = PropertiesConstants.getRaw(p,"value","");
        $dft = PropertiesConstants.getRaw(p,"dft","");
    }

    @Override
    protected void onExecute(final XsObject root, final XsObject current, final LogicletContext ctx, final ExecuteWatcher watcher){
        Terminal t = ctx.getObject(pid);
        if (t == null){
            throw new BaseException("core.e1001","It must be in a xshell context,check your together script.");
        }

        String cmd = PropertiesConstants.transform(ctx,$cmd,"");
        if (StringUtils.isNotEmpty(cmd)){
            BufferedResolver resolver = new BufferedResolver();
            t.exec(new Command.Simple(resolver,false,cmd));
            ctx.SetValue(id,resolver.getResult());
        }else{
            ctx.SetValue(id,PropertiesConstants.transform(ctx,$dft,""));
        }
    }

    public static class BufferedResolver implements Resolver{
        protected StringBuffer buf = new StringBuffer();

        public String getResult(){
            return buf.toString();
        }

        @Override
        public Object resolveBegin(String cmd) {
            buf.setLength(0);
            return buf;
        }

        @Override
        public void resolveLine(Object cookies, String content) {
            if (StringUtils.isNotEmpty(content)){
                if (buf.length() > 0){
                    buf.append("\n");
                }
                buf.append(content);
            }
        }

        @Override
        public void resolveEnd(Object cookies) {
        }
    }
}
